"""
various library utilities (also for compatibility with python2.4)
"""
try:
    from struct import Struct
except ImportError:
    import struct
    class Struct(object):
        __slots__ = ["format", "size"]
        def __init__(self, format):
            self.format = format
            self.size = struct.calcsize(format)
        def pack(self, *args):
            return struct.pack(self.format, *args)
        def unpack(self, data):
            return struct.unpack(self.format, data)

try:
    all = all
except NameError:
    def all(seq):
        for elem in seq:
            if not elem:
                return False
        return True

try:
    callable = callable
except NameError:
    def callable(obj):
        return hasattr(obj, "__call__")

#from threading import Lock as _Lock

#import thread
#import sys
#import itertools
#
#_thread_counter = itertools.count()
#_threads = {}
#def get_tid():
#    tid = thread.get_ident()
#    if tid not in _threads:
#        _threads[tid] = _thread_counter.next()
#    return _threads[tid]
#
#_lock_counter = itertools.count()
#class Lock(object):
#    def __init__(self, name = "", debug = False):
#        self._lock = _Lock()
#        self._debug = debug
#        self._name = "%s %d" % (name, _lock_counter.next())
#    def log(self, fmt, *args):
#        if not self._debug:
#            return
#        text = fmt % args if args else fmt
#        sys.stderr.write("[T%s L(%s)] %s\n" % (get_tid(), self._name, text))
#    def acquire(self, block = True):
#        self.log("acq")
#        ret = self._lock.acquire(block)
#        if ret:
#            self.log("ACQ")
#        else:
#            self.log("failed acq")
#        return ret
#    def release(self):
#        self.log("rel")
#        self._lock.release()
#        self.log("REL")

class MissingModule(object):
    __slots__ = ["__name"]
    def __init__(self, name):
        self.__name = name
    def __getattr__(self, name):
        raise ImportError("module %r not found" % (self.__name,))

def safe_import(name):
    try:
        mod = __import__(name, None, None, "*")
    except ImportError:
        mod = MissingModule(name)
    return mod





